<?php
class Functions
{
	public static function UrlArgs($str,$length=NULL,$isSecurity=TRUE)
	{
		$val=empty($_GET[$str]) ? NULL:$_GET[$str];
        
		if($val!=NULL){
			if($length!=NULL&&is_numeric($length)){
				$val=substr($val,0,(int)$length);
			}
			if($isSecurity==TRUE){
				$val=Functions::EncodeTags($val);
			}
		}
		return $val;
	}

	public static function FormArgs($str,$length=NULL,$isSecurity=TRUE)
	{
		$val = !empty($_POST[$str]) ? $_POST[$str] : NULL;
		if($val!=NULL){
			if($length!=NULL&&is_numeric($length)){
				$val=substr($val,0,(int)$length);
			}
			if($isSecurity==TRUE){
				$val=Functions::EncodeTags($val);
			}
		}
		return $val;
	}

	public static function HttpArgs($str,$length=NULL,$isSecurity=TRUE)
	{
		$val = !empty($_REQUEST[$str]) ? $_REQUEST[$str] : NULL;
		if($val!=NULL){
			if($length!=NULL&&is_numeric($length)){
				$val=substr($val,0,(int)$length);
			}
			if($isSecurity==TRUE){
				$val=Functions::EncodeTags($val);
			}
		}
		return $val;
	}

	public static function CookieArgs($str)
	{
		$val = !empty($_COOKIE[$str]) ? $_COOKIE[$str] : NULL;
		return $val;
	}

	/**
	 * 将字符串内容html实体化，避免一些非法信息直接执行。如果参数是数组，则递归。
	 * @param string $value
	 * @return array
	 */
	public static function EncodeTags($value)
	{
	    return is_array($value) ? array_map('Functions::EncodeTags', $value) :
			preg_replace('/&amp;((#(\d{3,5}|x[a-fA-F0-9]{4})|[a-zA-Z][a-z0-9]{2,5});)/', '&\\1', str_replace(array('&', '"', '<', '>'), array('&amp;', '&quot;', '&lt;', '&gt;'), $value));
	}

	/**
	 * 将字符串中的html去除，如果参数是数组，则递归。
	 * @param string $value
	 * @return array
	 */
	public static function StripTags($value)
	{
	    return $value = is_array($value) ? array_map('Functions::Striptags', $value) : strip_tags($value);
	}

	public static function PrintError($title,$err)
	{
		exit("<span style='font-size:20px;color:red;'>".$title."</span><hr/><span>".$err."</span>");
	}

	public static function PrintWarming($title,$err)
	{
		exit("<span style='font-size:20px;color:#ff9900;'>".$title."</span><hr/><span>".$err."</span>");
	}

	public static function Println($str)
	{
		echo $str.'<br/>';
	}

	public static function Zend_ExtractBody($str)
	{
		$parts=preg_split('|(?:\r?\n){2}|m',$response_str,2);
		if (isset($parts[1])) {
			return $parts[1];
		}
		return '';
	}

	public static function ParseArrayToQuerystring($array)
	{
		$tempStr='';
		foreach ($array as $key => $value)
		{
		    $tempStr.=($key.'='.$value.'&');
		}
		return substr($tempStr, 0, strlen($tempStr)-1);
	}

	public static function ParseNull($data)
	{
		if (chop($data)!='')
			if (strtolower(chop($data))=='null')
				return 'NULL';
			else
				return "'" . $data . "'";
		else
			return 'NULL';
	}

	public static function FileExt($filePath)
	{
		return end(explode('.', $filePath));
	}

	public static function UploadFile($fileObject,$options_path,$options_size=0,$options_type=array(),$options_autoName=true)
	{
		if(!empty($_FILES))
		{
			if(!empty($fileObject)&&in_array($fileObject,$_FILES))
			{
				$targetFileExtname= Functions::FileExt($fileObject['name']);
				$targetFilename=($options_autoName==true ? date('Ymd').time().rand(1000,2000).'.'. $targetFileExtname:$fileObject['name']);

				$tempFile=$fileObject['tmp_name'];
				$targetFile=str_replace('//','/',$options_path).$targetFilename;
				if(!empty($fileObject['name']))
				{
					//文件大小验证
					if($options_size!=0)
					{
						if(filesize($tempFile)==null||filesize($tempFile)>$options_size)
						{
							return array('Number'=>'2','Description'=>'文件超出规定大小');
						}
					}

					//扩展名验证
					if(count($options_type)>0)
					{
						if(!in_array($targetFileExtname,$options_type))
						{
							return array('Number'=>'3','Description'=>'文件格式不正确');
						}
					}

					//上传文件
					$isUpload=@move_uploaded_file($tempFile,$targetFile);
					if(!$isUpload)
						throw new Exception($_SERVER['SCRIPT_NAME'].' 未知错误。文件移动失败，请检查文件夹权限。'.$options_path);
					return array('Number'=>'0','Description'=>'上传完毕','FileName'=>$targetFilename);
				}
				else
				{
					return array('Number'=>'1','Description'=>'无文件');
				}
			}
			else
			{
				throw new Exception($_SERVER['SCRIPT_NAME'].' uploadFile函数上传文件出错。不是有有效的$_FILES成员');
			}
		}
		else
		{
			throw new Exception($_SERVER['SCRIPT_NAME'].' uploadFile函数上传文件出错。无$_FILES对象,请检查PHP配置环境。');
		}
	}

	public static function PhpHttpRequest($url,$parameters,$method)
	{
		$resultObject=Array('IsFsockopen'=>FALSE,'HttpStatus'=>0,'Result'=>'');

		$resp_str=NULL;
		$currentURL="http://".$_SERVER ['HTTP_HOST'].$_SERVER['PHP_SELF'];
		$url_=$url;
		$url = parse_url($url);

		$fp = @fsockopen($url['host'], $url['port'] ? $url['port'] : 80, $errno, $errstr, 10);

		if($fp)
		{
			fputs($fp,sprintf($method." %s%s%s HTTP/1.1\n", $url['path'], $url['query'] ? "?" : "", $url['query']));
			fputs($fp,"Host: $url[host]\n");
			fputs($fp,"Content-type: application/x-www-form-urlencoded\n");
			fputs($fp,"Content-length: " . strlen($parameters) . "\n");
			fputs($fp,"Referer:".$currentURL."\r\n");//伪造部分
			fputs($fp,"Connection: close\n\n");
			fputs($fp,"$parameters \n");

			while (!feof($fp))
			{
				$resp_str.=fgets($fp, 128);
			}
			fclose($fp);

			$httpStatus=substr($resp_str,9,3);

			$resultObject['IsFsockopen']=TRUE;
			$resultObject['HttpStatus']=$httpStatus;
			if($resultObject['HttpStatus']==403)
			{
				$temp=explode("\n",$resp_str);
				$resultObject['Result']=$temp[0];
			}
			else
			{
				$resultObject['Result']=Functions::Zend_ExtractBody($resp_str);
			}
		}
		return $resultObject;
	}

	public static function QueryWebservice_HTTP($url,$parameters,$method,$isHaveReturnValue=TRUE)
	{
		if($url==NULL) Functions::PrintError($_SERVER['SCRIPT_NAME'].' WebService调用失败。','错误信息：调用地址为NULL。');

		$response=Functions::PhpHttpRequest($url,$parameters,$method);

		if($response['IsFsockopen']==TRUE)
		{
			switch($response['HttpStatus'])
			{
				case 200:
				if($isHaveReturnValue==TRUE)
				{
					if($response['Result']==NULL)
					Functions::PrintError($_SERVER['SCRIPT_NAME'].' WebService调用失败，返回空值。','WebService地址=>'.$url.'<br/>错误信息，发起WebService请求的程式需要WebService返回值，但该调用并没回像我们期待的那样。<br/>情况1：WebService调用整常，但程序没有返回一个值。<br/>情况2：WebService程序在服务器执行过程中出现错误，出现这种情况就需要调式WebService程式了。');
				}
				return $response['Result'];
				break;

				case 403:
					Functions::PrintError($_SERVER['SCRIPT_NAME'].' WebService调用失败，服务器拒绝服务。','WebService地址=>'.$url.'<br/>错误信息：'.$response['Result']);
				break;

				case 404:
					Functions::PrintError($_SERVER['SCRIPT_NAME'].' WebService调用失败，找不到该服务地址。','WebService地址=>'.$url);
				break;

				case 500:
					Functions::PrintError($_SERVER['SCRIPT_NAME'].' WebService调用失败，服务器内部错误。','WebService地址=>'.$url.'<br/>错误信息：'.$response['Result']);
				break;

				default:
					Functions::PrintError($_SERVER['SCRIPT_NAME'].' WebService调用失败，这个错误是意料之外的。','WebService地址=>'.$url);
			}
		}
		else
		{
			Functions::PrintError($_SERVER['SCRIPT_NAME'].' WebService调用失败，服务器无效。','WebService地址=>'.$url);
		}
	}

	public static function SubStr($string,$length,$append=false)
	{
		if(strlen($string)<=$length)
		{
			return $string;
		}
		else
		{
			$i=0;

			while($i<$length)
			{
				$stringTMP=substr($string,$i,1);
				if(ord($stringTMP)>=224)
				{
					$stringTMP=substr($string,$i,3);
					$i=$i+3;
				}
				elseif(ord($stringTMP)>=192)
				{
					$stringTMP=substr($string,$i,2);
					$i=$i+2;
				}
				else
				{
					$i=$i+1;
				}
				$stringLast[] = $stringTMP;
			}

			$stringLast = implode('',$stringLast);
			if($append)
			{
				$stringLast.='...';
			}
			return $stringLast;
		}
	}
	
	public static function g_substr($str, $len = 12, $dot = true) 
	{
        $i = 0;
        $l = 0;
        $c = 0;
        $a = array();
        while ($l < $len) {
            $t = substr($str, $i, 1);
            if (ord($t) >= 224) {
                $c = 3;
                $t = substr($str, $i, $c);
                $l += 2;
            } elseif (ord($t) >= 192) {
                $c = 2;
                $t = substr($str, $i, $c);
                $l += 2;
            } else {
                $c = 1;
                $l++;
            }
            // $t = substr($str, $i, $c);
            $i += $c;
            if ($l > $len) break;
            $a[] = $t;
        }
        $re = implode('', $a);
        if (substr($str, $i, 1) !== false) {
            array_pop($a);
            ($c == 1) and array_pop($a);
            $re = implode('', $a);
            $dot and $re .= '...';
        }
        return $re;
    }

	public static function CreateFolders($dir)
	{
		return is_dir($dir) or (Functions::CreateFolders(dirname($dir)) and mkdir($dir, 0777));
	}

	public static function JsAlert($str)
	{
		echo '<script type="text/javascript">alert("'.$str.'");</script>';
	}

	public static function JsLocation($url,$target='_self')
	{
		if($target=='_self')
			echo '<script type="text/javascript">window.location="'.$url.'";</script>';
		else if($target=='_parent')
			echo '<script type="text/javascript">parent.window.location="'.$url.'";</script>';
		else if($target=='_top')
			echo '<script type="text/javascript">window.top.location="'.$url.'";</script>';
	}

	public static function JsHistory($step)
	{
		echo '<script type="text/javascript">history.go('.$step.');</script>';
	}

	public static function ParseNull_Implode(&$value)
	{
		return $value==NULL ? array():$value;
	}

	public static function GetFileFrom($pathName,$exts=false)
	{
		if($exts!=false)
		{
			for($i=0,$limits=count($exts);$i<$limits;$i++){
				$exts[$i]="*.".$exts[$i];
			}
		}
		$filter=!($exts) ? "*" : "{".implode($exts,",")."}";
		$pattern=$pathName."/".$filter;
		return glob($pattern,GLOB_BRACE);
	}

	/**
	 * 发送url请求 fsockopen
	 * 可以这样请求  ini::sendRequest('http://www.club-fish.com/doWhat.php',array("action"=>"addMoney", ... , ...)); 这个是同步请求会等返回值
	 * 也可以这样  ini::sendRequest('http://www.club-fish.com/doWhat.php?action=addMoney&xxx=yyy&zzz=xxx') 这样效果同上
	 * 这个就不一样了  ini::sendRequest('http://www.club-fish.com/doWhat.php',array(),TRUE)  这个是异步请求，不会有返回
	 *
	 * @param string $url 呼叫的url 注意数据可以直接附带在url上
	 * @param array $data [发送的数据 ]
	 * @param bool $async [是否是异步请求  默认false=同步  true=异步]
	 * @return string
	 */
	public static function SendRequest($url , $data = array() , $async = FALSE)
	{
		$error = NULL;//错误标志
		$url = parse_url($url);//分解url
		if (!$url) {
			$error ++ ;
			$results = "empty url";
		}else{
			if (!isset($url['port'])){
				$url['port'] = "";
			}
			if (!isset($url['query'])){
				$url['query'] = "";
			}
			$encoded = '';
			//接上额外的数据
			if (is_array($data) && count($data) > 0){
				foreach ($data as $k => $v){
					$encoded .= ($encoded ? "&" : "");
					$encoded .= rawurlencode($k)."=".rawurlencode($v);
				}
			}
			//打开资源
			$fp = fsockopen($url['host'], $url['port'] ? $url['port'] : 80);
			if (!$fp) {
				//出错：打不开资源
				$error ++ ;
				$results = "Failed to open socket to $url[host]";
			}else {
				//拼接head内容
				fputs($fp, sprintf("POST %s%s%s HTTP/1.0\n", $url['path'], $url['query'] ? "?" : "", $url['query']));
				fputs($fp, "Host: $url[host]\n");
				fputs($fp, "Content-type: application/x-www-form-urlencoded\n");
				fputs($fp, "Content-length: " . strlen($encoded) . "\n");
				fputs($fp, "Connection: close\n\n");
				//发送请求
				fputs($fp, "$encoded\n");

				if (!$async){
					//先或许些响应看请求是否成功
					$line = fgets($fp,1024);
					if (!eregi('^HTTP/1\.. 200', $line)) {
						//请求失败了
						$error ++ ;
						$results = "bad request";
					}else{
						//同步模式，
						//请求成功了，接着取所有的响应结果
						$results = "";
						$inheader = 1;
						while(!feof($fp))
						{
							$line = fgets($fp,1024);
							if ($inheader && ($line == "\n" || $line == "\r\n")){
								$inheader = 0;
							} elseif (!$inheader){
								$results .= $line;
							}
						}
					}
				}else {
					//异步请求无需返回
				}

				fclose($fp);
			}
		}
		//返回值或空
		if (empty($error)){
			return $results;
		}else {
			return NULL;
		}
	}

	public static function WriteFile($path,$file,$content,$method='w')
	{
		self::CreateFolders($path);
		$fp=fopen($path.$file,$method);
		{
			fwrite($fp,$content);
			fclose($fp);
		}
		$fp=NULL;
	}

	public static function FWriteFile($file,$content,$method='w')
	{
		$fp=fopen($file,$method);
		{
			fwrite($fp,$content);
			fclose($fp);
		}
		$fp=NULL;
	}

      public function Is_WholeNumber($value)
      {
            return ($value-abs($value))==0;
      }

      public function Is_ASSOC($arr)
      {
            return (count($arr)>0)&&(array_keys($arr)!==range(0, count($arr)-1));
      }

    public function SizeFormat($bytesize)
    {
        $i=0;
         //当$bytesize 大于是1024字节时，开始循环，当循环到第4次时跳出；
        while(abs($bytesize)>=1024){
        $bytesize=$bytesize/1024;
        $i++;
        if($i==4)break;
        }
        //将Bytes,KB,MB,GB,TB定义成一维数组；
        $units= array("bytes","kb","mb","gb","tb");
        $newsize=round($bytesize,2);
        return("$newsize $units[$i]");
    }

    public function CurrentURL()
    {
        $pageURL = 'http';

        if (@$_SERVER["HTTPS"] == "on")
        {
            $pageURL .= "s";
        }
        $pageURL .= "://";

        if ($_SERVER["SERVER_PORT"] != "80")
        {
            $pageURL .= $_SERVER["SERVER_NAME"] . ":" . $_SERVER["SERVER_PORT"] . $_SERVER["REQUEST_URI"];
        }
        else
        {
            $pageURL .= $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"];
        }
        return $pageURL;
    }

    public static function Print_r($data)
	{
			print_r($data);
			exit();
	}

    public static function GUID()
    {
        $charid = strtoupper(md5(uniqid(mt_rand(), true)));
        $hyphen = chr(45);// "-"
        $uuid = chr(123)// "{"
        .substr($charid, 0, 8).$hyphen
        .substr($charid, 8, 4).$hyphen
        .substr($charid,12, 4).$hyphen
        .substr($charid,16, 4).$hyphen
        .substr($charid,20,12)
        .chr(125);// "}"
        return $uuid;
    }

    public static function DateDiff($startDate,$endDate=NULL)
    {
        $startDate=strtotime($startDate);
        if(!$endDate){
            $endDate=strtotime(date('Y-m-d'));
        }

        return ($endDate-$startDate)/3600/24;
    }
	
	public static function HTTPRequest( 
		$verb = 'GET',             /* HTTP Request Method (GET and POST supported) */ 
		$ip,                       /* Target IP/Hostname */ 
		$port = 80,                /* Target TCP port */ 
		$uri = '/',                /* Target URI */ 
		$getdata = array(),        /* HTTP GET Data ie. array('var1' => 'val1', 'var2' => 'val2') */ 
		$postdata = array(),       /* HTTP POST Data ie. array('var1' => 'val1', 'var2' => 'val2') */ 
		$cookie = array(),         /* HTTP Cookie Data ie. array('var1' => 'val1', 'var2' => 'val2') */ 
		$custom_headers = array(), /* Custom HTTP headers ie. array('Referer: http://localhost/ */ 
		$timeout = 1,           /* Socket timeout in seconds */ 
		$req_hdr = false,          /* Include HTTP request headers */ 
		$res_hdr = false           /* Include HTTP response headers */ 
		) 
	{ 
		$ret = ''; 
		$verb = strtoupper($verb); 
		$cookie_str = ''; 
		$getdata_str = count($getdata) ? '?' : ''; 
		$postdata_str = ''; 
	
		foreach ($getdata as $k => $v) 
					$getdata_str .= urlencode($k) .'='. urlencode($v) . '&'; 
	
		foreach ($postdata as $k => $v) 
			$postdata_str .= urlencode($k) .'='. urlencode($v) .'&'; 
	
		foreach ($cookie as $k => $v) 
			$cookie_str .= urlencode($k) .'='. urlencode($v) .'; '; 
	
		$crlf = "\r\n"; 
		$req = $verb .' '. $uri . $getdata_str .' HTTP/1.1' . $crlf; 
		$req .= 'Host: '. $ip . $crlf; 
		$req .= 'User-Agent: Mozilla/5.0 Firefox/3.6.12' . $crlf; 
		$req .= 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8' . $crlf; 
		$req .= 'Accept-Language: en-us,en;q=0.5' . $crlf; 
		$req .= 'Accept-Encoding: deflate' . $crlf; 
		$req .= 'Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7' . $crlf; 
		
		foreach ($custom_headers as $k => $v) 
			$req .= $k .': '. $v . $crlf; 
			
		if (!empty($cookie_str)) 
			$req .= 'Cookie: '. substr($cookie_str, 0, -2) . $crlf; 
			
		if ($verb == 'POST' && !empty($postdata_str)) 
		{ 
			$postdata_str = substr($postdata_str, 0, -1); 
			$req .= 'Content-Type: application/x-www-form-urlencoded' . $crlf; 
			$req .= 'Content-Length: '. strlen($postdata_str) . $crlf . $crlf; 
			$req .= $postdata_str; 
		} 
		else $req .= $crlf; 
		
		if ($req_hdr) 
			$ret .= $req; 
		
		if (($fp = @fsockopen($ip, $port, $errno, $errstr)) == false) 
			return "Error $errno: $errstr\n"; 
		
		stream_set_timeout($fp, 0, $timeout * 1000); 
		
		fputs($fp, $req); 
		while ($line = fgets($fp)) $ret .= $line; 
		fclose($fp); 
		
		if (!$res_hdr) 
			$ret = substr($ret, strpos($ret, "\r\n\r\n") + 4); 
		
		return $ret; 
	}		
}
?>